package com.example.project.utils;

import com.example.project.aop.AuthLogin;
import com.example.project.enums.RoleEnum;
import com.example.project.exception.AuthException;
import com.example.project.vo.model.AuthUser;
import org.springframework.util.ObjectUtils;

public class AuthUtil {
    public static void checkLogin(AuthLogin authLogin) throws AuthException {


        AuthUser user = SecurityUtils.getUser();

        boolean need = authLogin.isNeed();
        if (need) {
            //需要登入

               user = SecurityUtils.getUser();
            if (ObjectUtils.isEmpty(user)) {
                throw new AuthException(401,"当前未登入！");
            }
        }


        RoleEnum[] roles = authLogin.roles();
        if (roles.length != 0 && roles != null) {

            RoleEnum role = user.getRole();
            if (ObjectUtils.isEmpty(role)) {
                throw new AuthException(403,"当前用户无权访问该接口！");
            }
            Boolean isRole = Boolean.FALSE;
            for (int i = 0; i < roles.length; i++) {

                RoleEnum roleEnum = roles[i];

                if (roleEnum.equals(role)) {
                    isRole = true;
                }
            }
            if (!isRole) {
                throw new AuthException(403,"当前用户无权访问该接口！");
            }

        }

    }
}
